package com.hdl.servlet.order;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayResponse;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.hdl.config.AlipayConfig;
import com.hdl.entity.MallOrder;
import com.hdl.service.MallOrderService;
import com.hdl.service.impl.MallOrderServiceImpl;

/**
 * PayfoAgainServlet 继续支付
 * @author Administrator
 *
 */
@WebServlet("/payforagain.let")
public class PayfoAgainServlet extends HttpServlet{

	private MallOrderService service = new MallOrderServiceImpl();
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		//获取参数
		String mallOrderId = req.getParameter("mallOrderId");
		
		//调用业务逻辑层方法
		MallOrder order = service.selectById(mallOrderId);
		
		//获取支付的配置信息
		AlipayConfig config = AlipayConfig.getConfig();
		//发起支付
		AlipayClient alipayClient = new DefaultAlipayClient(config.getGatewayUrl(), config.getAppId(), config.getMerchantPrivateKey(), "json", config.getCharset(), config.getAlipayPublicKey(), config.getSignType());

		//设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(config.getReturnUrl());
		alipayRequest.setNotifyUrl(config.getNotifyUrl());

		//商户订单号，商户网站订单系统中唯一订单号，必填
		String out_trade_no = order.getMallOrderNum();
		//付款金额，必填
		String total_amount = order.getMallOrderCash().toString();
		//订单名称，必填
		String subject = order.getMallOrderId();
		//商品描述，可空
		String body = "商品";

		String json = "{\"out_trade_no\":\""+ out_trade_no +"\"," 
				+ "\"total_amount\":\""+ total_amount +"\"," 
				+ "\"subject\":\""+ subject +"\"," 
				+ "\"body\":\""+ body +"\"," 
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}";

		alipayRequest.setBizContent(json);
		AlipayResponse res=null;
		try {
			res = alipayClient.pageExecute(alipayRequest);
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		req.setAttribute("body", res.getBody());


		//请求转发
		req.getRequestDispatcher("/pay.jsp").forward(req, resp);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
}
